package com.swjd.servlet;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.swjd.bean.sqlBean;

public class logincheck extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {	
        
   String message=null; 
   String id=null;
   id=req.getParameter("name1");
   HttpSession session=req.getSession(true);
   session.setAttribute("name1",String.valueOf(id));
   String password=null;
   password= req.getParameter("name2");
 
   String kind =null;
   kind=req.getParameter("name4");
   String temp =getPassword(req,res,id,kind);
   if( password.equals(temp))
   goo(req,res,kind);
   else {
 
   doError(req,res,message)	;}
 	} 
  
public void goo(HttpServletRequest req, HttpServletResponse res,String kind)
throws ServletException,IOException
{

	if(kind.equals("user")) {	
	RequestDispatcher rd = getServletContext().getRequestDispatcher("/user.jsp");
    rd.forward(req, res);}

    if(kind.equals("admin")){
    	RequestDispatcher rd = getServletContext().getRequestDispatcher("/admin.jsp");
    rd.forward(req, res);}
	}
	

  
     
  public String getPassword(HttpServletRequest req, HttpServletResponse res,
                        String id,String kind)
                        throws ServletException, IOException {
   sqlBean db= new sqlBean();                  	
   String pw="";
   if(kind.equals("user")){
   String sql="select password from "+kind+" where user_id='"+id+"'";
   try{
   ResultSet rs=db.executeQuery(sql); 	
   if(rs.next() ){
     pw= rs.getString("password");}
   	} 
   	catch(Exception e)
    { System.out.print(e.toString());}   	    
    //return pw; 
   }
   if(kind.equals("admin")){
	   String sql="select password from "+kind+" where admin_id='"+id+"'";
	   try{
	   ResultSet rs=db.executeQuery(sql); 	
	   if(rs.next() ){
	     pw= rs.getString("password");}
	   	} 
	   	catch(Exception e)
	    { System.out.print(e.toString());}   	    
	    //return pw; 
	   }

   return pw;
}
     
     	
      
public void doError(HttpServletRequest req,HttpServletResponse res,String str)
                      throws ServletException, IOException {
    req.setAttribute("problem", str);
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/errorpage.jsp");
    rd.forward(req, res);
  }
  
  
  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    	 String action = action = req.getParameter("action");
      if ("logout".equalsIgnoreCase(action)) {
      HttpSession session=req.getSession(true);
        session.invalidate();
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/hello.jsp");
        rd.forward(req, res);
        } 
      }
	
}

